#!/usr/bin/perl -w
# Extract tarballs
# vim:tw=100 sw=2 expandtab ft=perl

my %file_extract = flatten_hash(c("$hostname/file_extract"));
while (my($source, $f) = each(%file_extract)) {
  next unless i_should($source);
  $f->{dest} ||= "/";
  v "Skipping $source, $f->{check} exists" and next if $f->{check} && -e $f->{check};

  $source =~ s/^rollout:/$rollout_url/;

  l "Extracting $source to $f->{dest}";
  my $fn = $source;
  $fn =~ s/.*\///;
  w "Unknown filename $source" and next unless $fn;
  w "/tmp/$fn already exists, refusing to overwrite" and next if -f "/tmp/$fn";

  if (-x "/usr/bin/wget") {
    system("wget", $source, "-O", "/tmp/$fn") unless $safe_mode;
  } else {
    http_file -url => $source, -dest => "/tmp/$fn" unless $safe_mode;
  }

  dir_check($f->{dest}) unless $f->{dest} eq '/';
  chdir($f->{dest});

  if ($fn =~ /\.tar$/) {
    command("tar", "xf", "/tmp/$fn");
  } elsif ($fn =~ /\.tar\.gz$/) {
    command("tar", "zxf", "/tmp/$fn");
  } elsif ($fn =~ /\.tar\.bz2$/) {
    command("tar", "jxf", "/tmp/$fn");
  }

  unlink("/tmp/$fn");
}

